#pragma once

#include "thread_pool.hpp"
#include "tcp_server.hpp"
#include<unistd.h>
#include<unordered_map>
#include<sys/wait.h>
#include<pthread.h>

namespace ns_handler
{
	using namespace tcpserver;

	std::unordered_map<std::string,std::string> dict = 
	{
		{"apple","苹果"},
		{"hello","你好"},
		{"bit","比特"},
		{"viewsonic","优派"}
	};
	
	void Handler(int sock)
	{
		while(1)
		{
		char buffer[1024];
		ssize_t s = read(sock,buffer,sizeof(buffer)-1);
		if(s > 0)
		{
			buffer[s] = 0;
			std::cout<<"client say# "<<buffer<<std::endl;
			std::string k = buffer;
			std::string message = "我不知道";
			auto iter = dict.find(k);
			if(iter != dict.end())
			{
				message = iter->second;
			}
			write(sock,message.c_str(),message.size());
			std::cout<<"server echo# " <<message<<std::endl;
		}
		}
	}
	void Handlersock_v1(int sock)
	{
		Handler(sock);
	}
	void Handlersock_v2(int sock)
	{
		if(fork() == 0)
		{
			if(fork() > 0)
			{
				exit(0);
			}
			Handler(sock);
			exit(0);
		}
		waitpid(-1,nullptr,0);
	}
	void* thread_routine(void* args)
	{
		int sock = *(int*)args;
		delete(int*)args;
		pthread_detach(pthread_self());

		Handler(sock);
		close(sock);
		return nullptr;
	}
	void Handlersock_v3(int sock)
	{
		pthread_t tid;
		int *p = new int(sock);
		pthread_create(&tid,nullptr,thread_routine,p);
	}
	class task
	{
		private:
			int sock;
		public:
			task(){}
			task(int _sock):sock(_sock){}
			void operator()()
			{
				std::cout<<"当前处理的线程是:"<<pthread_self()<<std::endl;
				Handler(sock);
				close(sock);
			}
			~task(){}
	};
}
